package com.example.contactapp;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "contact.db";
    private static final int DATABASE_VERSION = 1;

    // User table
    public static final String TABLE_USER = "user";
    public static final String COLUMN_USER_ID = "_id";
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_PASSWORD = "password";

    // Contact table
    public static final String TABLE_CONTACT = "contact";
    public static final String COLUMN_CONTACT_ID = "_id";
    public static final String COLUMN_CONTACT_NAME = "name";
    public static final String COLUMN_CONTACT_ADDRESS = "address";
    public static final String COLUMN_CONTACT_PHONE = "phone";
    public static final String COLUMN_CONTACT_AGE = "age";
    public static final String COLUMN_CONTACT_INTERESTS = "interests";
    public static final String COLUMN_CONTACT_USER_ID = "user_id";

    private static final String CREATE_TABLE_USER = "CREATE TABLE " + TABLE_USER + " (" +
            COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            COLUMN_USERNAME + " TEXT NOT NULL UNIQUE," +
            COLUMN_PASSWORD + " TEXT NOT NULL)";

    private static final String CREATE_TABLE_CONTACT = "CREATE TABLE " + TABLE_CONTACT + " (" +
            COLUMN_CONTACT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            COLUMN_CONTACT_NAME + " TEXT NOT NULL," +
            COLUMN_CONTACT_ADDRESS + " TEXT," +
            COLUMN_CONTACT_PHONE + " TEXT NOT NULL," +
            COLUMN_CONTACT_AGE + " INTEGER," +
            COLUMN_CONTACT_INTERESTS + " TEXT," +
            COLUMN_CONTACT_USER_ID + " INTEGER," +
            "FOREIGN KEY(" + COLUMN_CONTACT_USER_ID + ") REFERENCES " + TABLE_USER + "(" + COLUMN_USER_ID + "))";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_USER);
        db.execSQL(CREATE_TABLE_CONTACT);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
        onCreate(db);
    }

    public long insertUser(String username, String password) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_USERNAME, username);
        values.put(COLUMN_PASSWORD, password);

        try {
            long id = db.insert(TABLE_USER, null, values);
            return id;
        } catch (Exception e) {
            Log.e("DatabaseHelper", "Error inserting user: " + e.getMessage());
            return -1;
        } finally {
            db.close();
        }
    }

    public long insertContact(String name,String address,String phone,int age,String interests,int userid){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_CONTACT_NAME,name);
        values.put(COLUMN_CONTACT_ADDRESS,address);
        values.put(COLUMN_CONTACT_PHONE,phone);
        values.put(COLUMN_CONTACT_AGE,age);
        values.put(COLUMN_CONTACT_INTERESTS,interests);
        values.put(COLUMN_CONTACT_USER_ID,userid);

        try {
            long id = db.insert(TABLE_CONTACT, null, values);
            return id;
        } catch (Exception e) {
            Log.e("DatabaseHelper", "Error inserting contact: " + e.getMessage());
            return -1;
        } finally {
            db.close();
        }

    }

    public boolean getUserByUsernameAndPassword(String username, String password) {
        SQLiteDatabase db = this.getReadableDatabase();

        String[] columns = {COLUMN_USER_ID};
        String selection = COLUMN_USERNAME + " = ? AND " + COLUMN_PASSWORD + " = ?";
        String[] selectionArgs = {username, password};

        Cursor cursor = db.query(TABLE_USER, columns, selection, selectionArgs, null, null, null);

        boolean exists = cursor.moveToFirst();
        cursor.close();
        db.close();

        return exists;
    }

    public List<Contact> getContactsByUserId(int userId) {
        List<Contact> contactList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();

        String[] columns = {
                COLUMN_CONTACT_ID,
                COLUMN_CONTACT_NAME,
                COLUMN_CONTACT_ADDRESS,
                COLUMN_CONTACT_PHONE,
                COLUMN_CONTACT_AGE,
                COLUMN_CONTACT_INTERESTS
        };

        String selection = COLUMN_CONTACT_USER_ID + " = ?";
        String[] selectionArgs = {String.valueOf(userId)};

        Cursor cursor = db.query(TABLE_CONTACT, columns, selection, selectionArgs, null, null, null);

        while (cursor.moveToNext()) {
            @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(COLUMN_CONTACT_ID));
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(COLUMN_CONTACT_NAME));
            @SuppressLint("Range") String address = cursor.getString(cursor.getColumnIndex(COLUMN_CONTACT_ADDRESS));
            @SuppressLint("Range") String phone = cursor.getString(cursor.getColumnIndex(COLUMN_CONTACT_PHONE));
            @SuppressLint("Range") int age = cursor.getInt(cursor.getColumnIndex(COLUMN_CONTACT_AGE));
            @SuppressLint("Range") String interests = cursor.getString(cursor.getColumnIndex(COLUMN_CONTACT_INTERESTS));

            Contact contact = new Contact(id, name, address, phone, age, interests);
            contactList.add(contact);
        }

        cursor.close();
        db.close();

        return contactList;
    }

    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACT, COLUMN_CONTACT_ID + "=?", new String[]{String.valueOf(contact.getId())});
        db.close();
    }


}